package com.example.oj.controller;//package com.example.ojquestion.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.oj.entity.Question;
import com.example.oj.entity.User;
import com.example.oj.entity.dto.question.QuestionQueryRequest;
import com.example.oj.entity.dto.question.QuestionSaveRequest;
import com.example.oj.service.QuestionService;
import com.example.ojcommon.annotation.AuthCheck;
import com.example.ojcommon.common.*;
import com.example.ojcommon.constant.UserConstant;
import com.example.ojcommon.exception.BusinessException;
import com.example.ojcommon.exception.ThrowUtils;
import com.example.oj.entity.vo.QuestionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 题目接口
 */
@RestController
@RequestMapping("/question")
//@Slf4j
public class QuestionController {

    @Resource
    private QuestionService questionService;

    /**
     * 创建题目
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQuestion(@RequestBody QuestionSaveRequest questionSaveRequest, HttpServletRequest request) {
        if (questionSaveRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionSaveRequest, question); // TODO 不要使用BeanUtils.copyProperties
        List<String> tags = questionSaveRequest.getTags();
        List<JudgeCase> judgeCaseList = questionSaveRequest.getJudgeCaseList();
        JudgeConfig judgeConfig = questionSaveRequest.getJudgeConfig();
        if (tags != null) {
            StringBuffer sb = new StringBuffer();
            tags.stream().forEach((item) -> {
                sb.append(item).append(",");
            });
            sb.deleteCharAt(sb.length() - 1);
            question.setTags(sb.toString());
        }
        if (judgeCaseList != null) {
            question.setJudgeCase(JSONUtil.toJsonStr(judgeCaseList));
        }
        if (judgeConfig != null) {
            question.setJudgeConfig(JSONUtil.toJsonStr(judgeConfig));
        }
        User user = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (Objects.isNull(user)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"用户未登录");
        }
        question.setUserId(user.getId());
        question.setIsQueried(questionSaveRequest.getIsQueried());
        questionService.saveOrUpdate(question);
        return ResultUtils.success(question.getId());
    }

    /**
     * 删除题目(仅管理员可删除)
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        boolean b = questionService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 修改题目（仅管理员）
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionSaveRequest questionUpdateRequest) {
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateRequest, question);
        List<String> tags = questionUpdateRequest.getTags();
        List<JudgeCase> judgeCaseList = questionUpdateRequest.getJudgeCaseList();
        JudgeConfig judgeConfig = questionUpdateRequest.getJudgeConfig();
        if (tags != null) {
            StringBuffer sb = new StringBuffer();
            tags.stream().forEach((item) -> {
                sb.append(item).append(",");
            });
            sb.deleteCharAt(sb.length() - 1);
            question.setTags(sb.toString());
        }
        if (judgeCaseList != null) {
            question.setJudgeCase(JSONUtil.toJsonStr(judgeCaseList));
        }
        if (judgeConfig != null) {
            question.setJudgeConfig(JSONUtil.toJsonStr(judgeConfig));
        }
        question.setIsQueried(questionUpdateRequest.getIsQueried());
        boolean b = questionService.saveOrUpdate(question);
        return ResultUtils.success(b);
    }

    /**
     * 根据 id 获取题目
     */
    @GetMapping("/getById")
    public BaseResponse<QuestionVO> getQuestionVOById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = questionService.getById(id);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(questionService.getQuestionVO(question));
    }

    /**
     * 分页获取列表（封装类）
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<QuestionVO>> listPageQuestionVO(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                             HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        List<Question> list = questionService.getQuestionPage(questionQueryRequest);
        Page<Question> questionPage = new Page<>(current, size);
        questionPage.setRecords(list);
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage));
    }

    @PostMapping("/list/competition")
    public BaseResponse<Page<QuestionVO>> listPageCompetitionQuestionVO(Long competitionId,HttpServletRequest request){
        Page<QuestionVO> list = questionService.listPageCompetitionQuestionVO(competitionId);
        return ResultUtils.success(list);
    }
}
